//
//  MajorViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/26.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "MajorViewController.h"
#import "define.h"
#import "PullLayout.h"
#import "ImageColl.h"
#import "UIImageView+WebCache.h"
#import "AsyncConnection.h"
#import "UIButton+WebCache.h"
#import "SpecailWebViewController.h"
#import "MJRefresh.h"

int n = 10648;
@interface MajorViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, assign) CGFloat offHeigt;
@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, retain) PullLayout *flow;


@end

@implementation MajorViewController

- (void)dealloc
{
    [_collection release];
    [_array release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.offHeigt = [[UIScreen mainScreen]bounds].size.height / 667;
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
    }
    return self;

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self beginConnection];
    self.title = @"新品推荐";
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    
    [self createCollectionView];
    // Do any additional setup after loading the view.
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)beginConnection
{
    NSDictionary *dic = @{@"more_items":@"1",
                          @"type":@"shop",
                          @"flag":@"",
                          @"gf":@"iphone",
                          @"gv":@"6.3.0"};
    
    [AsyncConnection asyncConnection:THREE_NEW parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self.array addObjectsFromArray:arr];
        
        _flow.layoutArr = self.array;
        [self.collection reloadData];
        
    }path:@"main_meirishangxin"];
}

- (void)createCollectionView
{
    self.flow = [[PullLayout alloc]init];
//    _flow.layoutArr = self.array;
//    _flow.minimumInteritemSpacing = 20;
//    _flow.minimumLineSpacing = 100;
    _flow.scrollDirection = UICollectionViewScrollDirectionVertical;

    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:_flow]
    ;
    self.collection.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.1];
    [self.view addSubview:self.collection];
    self.collection.delegate = self;
    self.collection.dataSource = self;
//    self.collection.bounces = NO;
    [self.collection registerClass:[ImageColl class] forCellWithReuseIdentifier:@"co"];
    [self.collection release];
    
    [self addFooter];
    
}

- (void)addFooter
{
    __block MajorViewController *actionVC = self;
    
    [self.collection addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSDictionary *dic = @{@"more_items":@"1",
                                  @"type":@"shop",
                                  @"flag":[NSString stringWithFormat:@"%d", n],
                                  @"gf":@"iphone",
                                  @"gv":@"6.3.0"};
            [AsyncConnection asyncConnection:THREE_NEW parmaters:dic block:^(NSData *data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray *arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
                if (arr.count == 0) {
                    [self.collection footerEndRefreshing];
                }else
                {
                    [self.array addObjectsFromArray:arr];
                     _flow.layoutArr = self.array;
                    [actionVC.collection reloadData];
                    
                }
               n -= 18;
            }path:@"main_meirishangxin"];
            [self.collection footerEndRefreshing];
        });
    }];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    NSLog(@"%ld", self.array.count);
    return self.array.count - 1;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageColl *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"co" forIndexPath:indexPath];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5*_offWidth, 5* _offHeigt, 180*_offWidth, 40* _offHeigt)];
    [self.collection addSubview:label];
    UILabel *day = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40*_offWidth, label.frame.size.height)];
    [label addSubview:day];
    day.text = [[[self.array objectAtIndex:0]objectForKey:@"component"]objectForKey:@"day"];
    day.font = [UIFont systemFontOfSize:30];
    
    UILabel *month = [[UILabel alloc]initWithFrame:CGRectMake(40 * _offWidth, 0, 40*_offWidth, label.frame.size.height / 2)];
    
    [label addSubview:month];
    month.textColor = [UIColor lightGrayColor];
    month.text = [[[self.array objectAtIndex:0]objectForKey:@"component"]objectForKey:@"weekDay"];
    [month release];
    UILabel *week = [[UILabel alloc]initWithFrame:CGRectMake(40 *_offWidth, label.frame.size.height / 2, 40 *_offWidth, label.frame.size.height / 2)];
    week.textColor = [UIColor lightGrayColor];
    [label addSubview:week];
    week.text = [@"/" stringByAppendingString:[[[self.array objectAtIndex:0]objectForKey:@"component"]objectForKey:@"monthOnly"]];
    [week release];
    
    UILabel *quan = [[UILabel alloc]initWithFrame:CGRectMake(100*_offWidth, 0, 80*_offWidth, label.frame.size.height / 2)];
    [label addSubview:quan];
    quan.textColor = [UIColor lightGrayColor];
    quan.text = @"全球新品推荐";
    quan.textAlignment = 2;
    quan.font = [UIFont systemFontOfSize:12];
    
    UILabel *date = [[UILabel alloc]initWithFrame:CGRectMake(100*_offWidth, label.frame.size.height / 2, 50*_offWidth, label.frame.size.height / 2)];
    [label addSubview:date];
    date.textAlignment = 2;
    date.font = [UIFont systemFontOfSize:12];
    date.textColor = [UIColor colorWithRed:255/255 green:0 blue:255/255 alpha:0.5];
    date.text = [[[self.array objectAtIndex:0]objectForKey:@"component"]objectForKey:@"showTime"];
    [date release];
    [quan release];
    UILabel *fabu = [[UILabel alloc]initWithFrame:CGRectMake(150*_offWidth, label.frame.size.height / 2, 30*_offWidth, label.frame.size.height / 2)];
    [label addSubview:fabu];
    fabu.textAlignment = 2;
    fabu.font = [UIFont systemFontOfSize:12];
    fabu.textColor = [UIColor lightGrayColor];
    fabu.text = @"发布";
    
    [label release];


    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    
    if (indexPath.item != 0) {
        NSDictionary *dic = [[self.array objectAtIndex:indexPath.item]objectForKey:@"component"];
        NSString *pic = [[[[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"picUrl"] componentsSeparatedByString:@"?"]objectAtIndex:0];
        [cell.image sd_setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        cell.title.text = [dic objectForKey:@"description"];
        cell.price.text = [@"￥" stringByAppendingString:[dic objectForKey:@"price"]];
//        [cell.source sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"nationalFlag"]] forState:UIControlStateNormal];
        
        
//        [cell.source setTitle:[dic objectForKey:@"country"] forState:UIControlStateNormal];
    }
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SpecailWebViewController *specail = [[SpecailWebViewController alloc]init];
    specail.dic = [[self.array objectAtIndex:indexPath.item]objectForKey:@"component"];
    specail.height = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"height"]floatValue];
    specail.width = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"width"]floatValue];
    specail.wid = [[[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"action"]objectForKey:@"sourceId"];
    [self.navigationController pushViewController:specail animated:YES];
    [specail release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
